import axios from 'axios'
import { messageInstance, getToken } from '../util/method'
import { mscf } from '../util/const'
export let BASE_URL = process.env.BASE_URL

export const uploadImgUrl = process.env.BASE_URL + '/anchor/platform/anchors/common/upload'

console.log(process.env.BASE_URL)
let instance = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 60000,
  headers: {
    Authorization: getToken()
  }
})

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const body = response.data || {}
    const { code, message, errMessage } = body
    // 文件流
    if (response.config.responseType && response.config.responseType === 'arraybuffer') {
      let blobStr = new Blob([response.data])
      return blobStr
    }

    switch (code) {
      case 1002:
      case 1001:
        let msg = message || errMessage
        messageInstance.error(msg)
        return Promise.reject(msg)
      case 500:
        return Promise.reject(new Error('processed'))
      case 401:
      case 400:
        mscf.emit('loginExpire', '*', {}) // TODO 告诉父应用，登录已经过期
        return Promise.reject(new Error('processed'))
      default:
        return body.data // TODO 直接返回数据，业务不用关心code和message
    }
  },
  (error) => {
    const { response: { status = '', data: { msg, message } = {} } = {} } = error
    // 默认提示服务端返回文案
    let txt = msg || status + '接口异常'
    if (status === 404) txt = '未找到api'
    // 500 && 服务端有提示文案
    if (status === 500 && message) txt = message

    messageInstance.error(txt)
    return Promise.reject(error)
  }
)
// instance.interceptors.response.use((res) => {
//   console.log(res)
//   // 这里可以对响应做预处理
//   if (res.code && res.code.toString() === '10001') {
//     return Promise.reject(new Error('用户失效'))
//   }
//   return res
// })

export const http = instance
